﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace EmployeeCheckIn
{
    public partial class EditAdmin : System.Web.UI.Page
    {
        StringBuilder sb = new StringBuilder();
        string PassDB;
        string UserDB;
        string NowUserDB;
        int test=0;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["User"] != null && Session["Pass"] != null )
            {
                if (IsPostBack && txtOldPass.Text != string.Empty && test == 0)
                {
                    txtOldPass.Attributes["value"] = txtOldPass.Text;
                }
                
                if (IsPostBack && txtNewpass.Text != string.Empty && test == 0)
                {
                    txtNewpass.Attributes["value"] = txtNewpass.Text;
                }
                
                if (IsPostBack && txtComfirmPass.Text != string.Empty && test == 0)
                {
                    txtComfirmPass.Attributes["value"] = txtComfirmPass.Text;
                }
                if (IsPostBack)
                {
                    int i = Convert.ToInt32(Session["admin_id"]);
                    Selectdata sl = new Selectdata();
                    DataTable dt = sl.SelectAdminData(i);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        NowUserDB = dt.Rows[0]["user_name"].ToString();
                       
                    } 
                }
                if (!IsPostBack)
                {
                    
                    int i = Convert.ToInt32(Session["admin_id"]);
                    Selectdata sl = new Selectdata();
                    DataTable dt = sl.SelectAdminData(i);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        txtUserName.Text = dt.Rows[0]["user_name"].ToString();
                        NowUserDB = dt.Rows[0]["user_name"].ToString();
                        txtAdminName.Text = dt.Rows[0]["admin_name"].ToString();
                        txtAdminLastName.Text = dt.Rows[0]["admin_lastname"].ToString();
                        txtPhone.Text = dt.Rows[0]["admin_phone"].ToString();
                        //lbEditTime.Text = Convert.ToDateTime(dt.Rows[0]["admin_date_regis"].ToString()).ToString("dd/MM/yyyy HH:MM:ss", new System.Globalization.CultureInfo("th-TH"));

                    }
                }

            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
        private void lbEmpty()
        {
            lbWarnAdminName.Visible = false;
            lbWarnNum.Visible = false;
            lbWarnPhone.Visible = false;
            lbWrnNewpass.Visible = false;
            lbWrnOldpass.Visible = false;
            Label1.Visible = false;
            lbWarnlsn.Visible = false;
        }
        public void UpdatePass(Log_inEntity enLog, string old_user)
        {

            string sqltext = @"UPDATE TBL_LOG_IN
                               SET USER_PASSWORD =@user_password
                               WHERE USER_NAME = '" + old_user + "'";


            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            sqlcomm.Connection = sqlconn;
            sqlcomm.CommandType = System.Data.CommandType.Text;
            sqlcomm.CommandText = sqltext;
            sqlcomm.Parameters.AddWithValue("@user_password", enLog.password);

            try
            {
                sqlcomm.Connection.Open();
                sqlcomm.ExecuteNonQuery();
            }
            catch (Exception)
            {

                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
            }
            sqlcomm.Connection.Close();
            sqlcomm.Connection.Dispose();

        }

        protected void btsumitChange_Click(object sender, EventArgs e)
        {
            lbEmpty();
            if (Session["User"] != null && Session["Pass"] != null)
            {
                Log_in in_log = new Log_in();
                Log_inEntity Enlog = new Log_inEntity();
                string U = Session["User"].ToString();
                string P = EncyptMd5.getMd5Hash(txtOldPass.Text);
                bool resualt = false;
                DataTable dt = in_log.GetData(U, P);

                if (dt != null && dt.Rows.Count > 0)
                {
                    //ยืนยันรหัสเดิมถูกต้อง
                    UserDB = dt.Rows[0]["user_name"].ToString();
                    PassDB = dt.Rows[0]["user_password"].ToString();

                    if (txtNewpass.Text != txtComfirmPass.Text)
                    {
                        lbWrnNewpass.Visible = true;
                        lbWrnOldpass.Visible = false;
                        lbWarnNum.Visible = false;
                        resualt = true;
                        //NewPassFial 
                    }
                    if (txtNewpass.Text.Length < 8)
                    {
                        lbWarnNum.Visible = true;
                        lbWrnNewpass.Visible = false;
                        lbWrnOldpass.Visible = false;
                        resualt = true;
                    }
                    if (txtNewpass.Text == txtComfirmPass.Text && txtNewpass.Text.Length >= 8)
                    {
                        //NEW PASSWORD CORRECT
                        Enlog.password = EncyptMd5.getMd5Hash(txtNewpass.Text);
                        UpdatePass(Enlog, UserDB);
                        lbWrnOldpass.Visible = false;
                        lbWrnNewpass.Visible = false;
                        lbWarnNum.Visible = false;
                        resualt = false;

                    }


                }

                if (!(dt != null && dt.Rows.Count > 0))
                {
                    //ยืนยันรหัสเดิมไม่ถูกต้อง
                    lbWrnOldpass.Visible = true;
                    lbWrnNewpass.Visible = false;
                    resualt = true;
                    //OldPassFial
                }
                if (resualt == true)
                {
                    return;
                }
                if (resualt == false)
                {
                    Response.Write("<script>alert('แก้ไขรหัสผ่านเรียบร้อยแล้ว!'); window.location='EditAdmin.aspx';</script>");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");

            }


        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                
                test = 1;
                if (IsPostBack && txtOldPass.Text != string.Empty && test == 1)
                {
                    txtOldPass.Attributes["value"] = "";
                }
                if (IsPostBack && txtNewpass.Text != string.Empty && test == 1)
                {
                    txtNewpass.Attributes["value"] = "";
                }
                if (IsPostBack && txtComfirmPass.Text != string.Empty && test == 1)
                {
                    txtComfirmPass.Attributes["value"] = "";
                }
            }

            else
            {
                Response.Redirect("Default.aspx");
            }
        }
        public void UpdateName(Log_inEntity enLog, int id)
        {

            string sqltext = @"UPDATE TBL_LOG_IN
                               SET USER_NAME   = @user_name
                                ,ADMIN_NAME     = @admin_name
                                ,ADMIN_LASTNAME = @admin_lastname
                                ,ADMIN_phone    = @admin_phone
                                ,ADMIN_DATE_EDIT = GETDATE()
                                ,update_By = @update_by
                                
                               WHERE ADMIN_ID = " + id + "";


            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            sqlcomm.Connection = sqlconn;
            sqlcomm.CommandType = System.Data.CommandType.Text;
            sqlcomm.CommandText = sqltext;
            sqlcomm.Parameters.AddWithValue("@user_name", enLog.username);
            sqlcomm.Parameters.AddWithValue("@admin_name", enLog.adminNAME);
            sqlcomm.Parameters.AddWithValue("@admin_lastname", enLog.adminLASTNAME);
            sqlcomm.Parameters.AddWithValue("@admin_phone", enLog.adminPHONE);
            sqlcomm.Parameters.AddWithValue("@update_by", enLog.updateBy);

            try
            {
                sqlcomm.Connection.Open();
                sqlcomm.ExecuteNonQuery();
            }
            catch (Exception)
            {

                sqlcomm.Connection.Close();
                sqlcomm.Connection.Dispose();
            }
            sqlcomm.Connection.Close();
            sqlcomm.Connection.Dispose();

        }
        public bool checknumber(string s)
        {
            //bool result = false;
            //string Str = s.Trim();
            //double Num;
            //bool isNum = double.TryParse(Str, out Num);
            //if (isNum)
            //{ 
            //    result = true; 
            //}
            //return result;

            bool result = false;
            try
            {
                Convert.ToInt32(s);
                result = true;
            }
            catch (Exception)
            {
                result = false;

            }
            return result;
        }
        public DataTable GetUserNameInDb(string U)
        {

            DataTable dt = new DataTable();
            string sqltext = "select * from TBL_LOG_IN Where user_name like '" + U + "'; ";
            SqlConnection sqlconn = new SqlConnection("Server=202.44.52.248;Database=DB_Personal;User Id=personal;Password=1234;");
            SqlDataAdapter da = new SqlDataAdapter(sqltext, sqlconn);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        protected void btChangeName_Click(object sender, EventArgs e)
        {
            Log_inEntity enLog = new Log_inEntity();
            int i = Convert.ToInt32(Session["admin_id"]);
            lbEmpty();
            bool resault = true;
            
            string Username = txtUserName.Text;
            DataTable dt = GetUserNameInDb(Username);
            if (dt != null && dt.Rows.Count > 0)
            {
                if (Username == NowUserDB)
                {
                    resault = true;
                }
                else
                {
                    //string UserDB = dt.Rows[0]["user_name"].ToString();
                    lbWarnHaveUser.Visible = true;
                    resault = false;
                    //username avalible  
                }
            }   
            if (txtUserName.Text == "")
            {
                Label1.Visible = true;
                resault = false;
            }
            if (txtAdminName.Text == "")
            {
                lbWarnAdminName.Visible = true;
                resault = false;
            }
            if (txtAdminLastName.Text == "")
            {
                lbWarnlsn.Visible = true;
                resault = false;
            }
            if (checknumber(txtPhone.Text) == false)
            {
                if (txtPhone.Text=="")
                {
                   resault = true;  
                }
                else
                {
                    lbWarnPhone.Visible = true;
                    resault = false;
                }
            }
            if (resault == false)
            {
                return;
            }
            if (resault == true)
            {
                enLog.username = txtUserName.Text;
                enLog.adminNAME = txtAdminName.Text;
                enLog.adminLASTNAME = txtAdminLastName.Text;
                enLog.adminPHONE = txtPhone.Text;
                Session["User"] = enLog.username;
                enLog.updateBy = Session["User"].ToString();
                UpdateName(enLog, i);
                Response.Write("<script>alert('แก้ไขข้อมูลเรียบร้อยแล้ว!'); window.location='EditAdmin.aspx';</script>");
            }

        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                int i = Convert.ToInt32(Session["admin_id"]);
                Selectdata sl = new Selectdata();
                DataTable dt = sl.SelectAdminData(i);
                if (dt != null && dt.Rows.Count > 0)
                {
                    txtUserName.Text = dt.Rows[0]["user_name"].ToString();
                    txtAdminName.Text = dt.Rows[0]["admin_name"].ToString();
                    txtAdminLastName.Text = dt.Rows[0]["admin_lastname"].ToString();
                    txtPhone.Text = dt.Rows[0]["admin_phone"].ToString();
                }

                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            if (Session["User"] != null && Session["Pass"] != null)
            {
                Server.Transfer("MenuAdmin.aspx");
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }
    }
}